用react&拆分项目webpack4; html标签是意外标记 [英] Splitting up project with react & webpack4; html tags are unexpected tokens

查看:76
本文介绍了用react&拆分项目webpack4; html标签是意外标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

我正在使用react,babel,webpack4和es6(或可能是es7)

我有一些模块可以被多个React项目重用.因此,我创建了一个标准"文件夹,其中包含这些模块,以使它们与任何特定项目分开.

问题

在我的react项目中,我将webpack.config.js编辑为包含

  resolve: {
    extensions: ['.css', '.js', '.jsx'],
    alias: {
      Standard: '/Path/To/Standard',
    }
  }

然后从我调用的模块中导入模块

import MyModule from 'Standard/MyModule.js'

执行此操作时,似乎在我的标准文件夹中的文件中无法识别html标记

错误消息

对于webpack-dev-server --inline

ERROR in /Path/To/Standard/MyModule.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Path/To/Standard/MyModule.js: Unexpected token (13:8)

  11 | var MyModule = (props) => {
  12 |     return (
> 13 |         <header id='Header' className={props.className}>

对于webpack

npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! default@1.0.0 build: `webpack`
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the default@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.


调试尝试

我尝试在我的标准文件夹(除了我的项目文件夹)中创建一个webpack.config.js和package.json,但是似乎没有任何帮助

我尝试了一些npm安装来安装babel,因为这似乎是最明显的解决方案,在较旧的webpack版本中对此问题进行解答,但我仍然遇到相同的问题

  npm install --save react
  npm install --save babel @babel/cli @babel/core @babel/preset-env @babel/preset-react
  npm install --save babel-core babel-loader babel-cli babel-preset-env babel-preset-react webpack

看起来也像

webpack.config.js

 var webpack = require('webpack');

const config = {
    mode: 'development',     // set mode option, 'development' or 'production'
    module: {
      rules: [
        {
          test: /\.m?js$/,
          exclude: /(node_modules|bower_components)/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env']
            }
          }
        }
      ]
    },
    resolve: {
      extensions: ['.css', '.js', '.jsx'],
    }
}

module.exports = config; 

.babelrc

 {
  "presets": ["@babel/preset-env", "@babel/preset-react"],
  "plugins": [
    [
      "@babel/plugin-proposal-class-properties",
      {
        "loose": true
      }
    ]
  ]
} 

解决方案

您的第一个问题是babel不能从您的程序包中解析代码(错误说它试图执行未编译的jsx代码)./p>

也许在您的软件包目录中无法访问babel预设. 您可以尝试复制它们或直接在webpack配置中设置它们

                    {
                        loader : 'babel-loader',
                        options: {
                            presets       : [
                                ['@babel/preset-env',
                                    {// here the presets params
                                    }],
                                '@babel/preset-react'
                            ],
                            plugins       : [
                                ['@babel/plugin-proposal-class-properties', {
                                    "loose": true
                                }]
                            ]
                        }
                    },

可能,babel的exclude regexp排除了要从中导入脚本的软件包:

     exclude: /(node_modules|bower_components)/,

因此您可以使用这样的自定义函数:

     exclude: {test:(pathName)=>(isInternalCode(pathName))),

或在reg exp中使用负前瞻:

/(node_modules(?!\ b(?:OneFolder | AnotherIncluded))| bower_modules)/

这就是说,通常的方法是独立编译您的程序包(通过从构建中外部化其所有dep并将其添加到"peerDependencies"或"dependencies"中)

也;有一个用于制作可继承"程序包的插件; 图层包.

它允许制作可继承的"项目,&处理node_modules&制作可继承的代码层"的Webpack&甚至在编译节点脚本或使用monorepo结构时也可以工作

使用它,您可以简单地将组件放在共享的可继承程序包中

它具有一些不错的功能,例如全局解析,该功能有助于包括未知数量的文件.

此处有示例doc 此处

希望对您有所帮助:)

Background

I'm using react, babel, webpack4, and es6(or maybe es7)

I have some modules that are reused by multiple react projects. For this reason I've created a 'Standard' folder that contains these modules so that they are kept separate from any specific project.

Problem

In my react project I edited my webpack.config.js to contain

  resolve: {
    extensions: ['.css', '.js', '.jsx'],
    alias: {
      Standard: '/Path/To/Standard',
    }
  }

Then to import a module from it I call

import MyModule from 'Standard/MyModule.js'

When I do this, it looks like the html tags aren't recognized within the files in my Standard folder

Error Messages

For webpack-dev-server --inline

ERROR in /Path/To/Standard/MyModule.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Path/To/Standard/MyModule.js: Unexpected token (13:8)

  11 | var MyModule = (props) => {
  12 |     return (
> 13 |         <header id='Header' className={props.className}>

For webpack

npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! default@1.0.0 build: `webpack`
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the default@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.


Debugging attempts

I've tried to create a webpack.config.js and package.json inside my standard folder(in addition to my project folder), but nothing really seems to help

I tried some npm installs to install babel, because that seemed like the most obvious solution, and is used on this answer in an older webpack version, but I still get the same problems

  npm install --save react
  npm install --save babel @babel/cli @babel/core @babel/preset-env @babel/preset-react
  npm install --save babel-core babel-loader babel-cli babel-preset-env babel-preset-react webpack

Also it looks like this post which is a reply to this blog might be related, but this solution didn't work for me.


package.json

{
    "scripts": {
        "webpack": "webpack",
        "start": "http-server"
    },
    "dependencies": {
        "react": "^16.8.6"
    },
    "devDependencies": {
        "@babel/cli": "^7.5.5",
        "@babel/core": "^7.5.5",
        "@babel/plugin-proposal-object-rest-spread": "^7.5.1",
        "@babel/polyfill": "^7.4.4",
        "@babel/preset-env": "^7.5.0",
        "@babel/preset-react": "^7.0.0",
        "babel-loader": "^8.0.6",
        "webpack": "^4.28.0"
    }
}

webpack.config.js

var webpack = require('webpack');

const config = {
    mode: 'development',     // set mode option, 'development' or 'production'
    module: {
      rules: [
        {
          test: /\.m?js$/,
          exclude: /(node_modules|bower_components)/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env']
            }
          }
        }
      ]
    },
    resolve: {
      extensions: ['.css', '.js', '.jsx'],
    }
}

module.exports = config;

.babelrc

{
  "presets": ["@babel/preset-env", "@babel/preset-react"],
  "plugins": [
    [
      "@babel/plugin-proposal-class-properties",
      {
        "loose": true
      }
    ]
  ]
}

解决方案

You're 1st problem here is that babel is not parsing code from you're packages (error say that it try to exec not transpiled jsx code).

Maybe the babel presets is not accessible in you're package directory. You can try copying them or set them directly in the webpack config

                    {
                        loader : 'babel-loader',
                        options: {
                            presets       : [
                                ['@babel/preset-env',
                                    {// here the presets params
                                    }],
                                '@babel/preset-react'
                            ],
                            plugins       : [
                                ['@babel/plugin-proposal-class-properties', {
                                    "loose": true
                                }]
                            ]
                        }
                    },

Possibly the exclude regexp of babel exclude the packages from where you want importing scripts :

     exclude: /(node_modules|bower_components)/,

So you can use a custom function like that :

     exclude: {test:(pathName)=>(isInternalCode(pathName))),

Or use negative lookahead in the reg exp like :

/(node_modules(?!\b(?:OneFolder|AnotherIncluded))|bower_modules)/

That's said the usual way is to compile independently you're packages ( by externalizing all theirs deps from the builds & adding them to "peerDependencies" or "dependencies" )

Also; there a plugin to make "inheritable" packages; layer-pack.

It allow making "inheritable" projects, & deal with node_modules & webpack to make inheritable "code layers" & even work when compiling node scripts or using monorepo structure

Using it you can simply put you're components in a shared inheritable package

it come with some nice features like glob resolving, which help including an unknown number of files.

There is samples here & doc here

Hope it help :)

这篇关于用react&amp;拆分项目webpack4; html标签是意外标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆